from PySide6.QtWidgets import QWidget,QTableWidgetItem,QFileDialog,QMessageBox,QMenu,QAbstractItemView,QHeaderView
from PySide6.QtCore import Qt
from views.salary.salaryscale.salaryscale import Ui_salaryscale
from views.salary.salaryscale.operationsalaryscaleView import OperationSalaryScale
from views.person.model.person import PersonBaseInfo
from sqlalchemy.orm import Session
from settings.publicvar import engine
from views.salary.model.salary import SalaryScale
import os,shutil,pandas as pd

class SalaryscaleView(QWidget,Ui_salaryscale):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.salaryscaletable.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.salaryscaletable.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.salaryscaletable.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
        self.salaryscaletable.setContextMenuPolicy(Qt.CustomContextMenu)
        self.salaryscaletable.customContextMenuRequested.connect(self.generate_menu)

        self.load_table_data()
        self.downloadmodle.clicked.connect(self.downloadmodleFun)
        self.serearchbtn.clicked.connect(self.serearchFun)
        self.sereachedit.editingFinished.connect(self.serearchFun)
        self.importbtn.clicked.connect(self.importdataFun)
        self.addsalaryscale.clicked.connect(self.additem)

    # 表格结构
    def setTableStructure(self, data):
        self.salaryscaletable.setRowCount(len(data))
        for i, item in enumerate(data):
            idx = QTableWidgetItem(str(item.id))
            self.salaryscaletable.setItem(i, 0, idx)
            name = QTableWidgetItem(item.personbase.name)
            self.salaryscaletable.setItem(i, 1, name)
            salaryscale_level = QTableWidgetItem(item.salaryscale_level)
            self.salaryscaletable.setItem(i, 2, salaryscale_level)
            salaryscale_date = QTableWidgetItem(str(item.salaryscale_date))
            self.salaryscaletable.setItem(i, 3, salaryscale_date)
            salaryscale_type = QTableWidgetItem(item.salaryscale_type)
            self.salaryscaletable.setItem(i, 4, salaryscale_type)
            mark = QTableWidgetItem(item.mark)
            self.salaryscaletable.setItem(i, 5, mark)

    # 数据加载
    def load_table_data(self):
        with Session(engine) as session, session.begin():
            salaryscales = session.query(SalaryScale).all()
            self.setTableStructure(salaryscales)

    def downloadmodleFun(self):
        model_file_path = "state/model/薪级情况模板.xlsx"
        model_file_name = os.path.basename(model_file_path)
        save_path,_ = QFileDialog.getSaveFileName(self,'下载模板',model_file_name,f"(*.{model_file_name.split('.')[-1]})")
        shutil.copy2(model_file_path, save_path)
        QMessageBox.information(None,'下载成功','恭喜你下载成功！')

    def serearchFun(self):
        sereachdata = self.sereachedit.text().strip()
        if sereachdata == '':
            QMessageBox.critical(None, '错误', '搜索框不能为空！')
            self.load_table_data()
        else:
            with Session(engine) as session, session.begin():
                sereachName = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.name.like('%' + sereachdata + '%')).all()
                sereachIDcard = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.IDcard.like('%' + sereachdata + '%')).all()
                sereachiphone = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.iphone.like('%' + sereachdata + '%')).all()
                sereachData = sereachName + sereachIDcard + sereachiphone
                others = []
                if sereachData:
                    for personbase in sereachData:
                        for other in personbase.salaryscales:
                            others.append(other)
                    # 数据处理和加载QTable表
                    self.setTableStructure(others)
                else:
                    QMessageBox.critical(None,'没有数据','你搜索数据不存在！')

    # 导入数据处理
    def importdataFun(self):
        url, a = QFileDialog.getOpenFileUrl(self, '导入数据')
        try:
            data = pd.read_excel(url.toLocalFile(), sheet_name=0, header=1,
                                 names=['idx','name','IDcard','salaryscale_level','salaryscale_date','salaryscale_type','mark'],
                                 dtype={'IDcard': str},
                                 parse_dates=['salaryscale_date']).drop('idx', axis=1)
            data = data.where(data.notna(), '')
            data['salaryscale_date'] = data['salaryscale_date'].replace({pd.NaT: None})
            with (Session(engine) as session, session.begin()):
                qury_exist_personbase_tem = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.IDcard.in_(data.IDcard.to_list())).all()
                tem = []
                for item in qury_exist_personbase_tem:
                    tem.append((item.IDcard, item.id))
                if len(tem) > 0:
                    qury_exist_personbase_tem = tem
                    qury_exist_personbase = [tem[0] for tem in qury_exist_personbase_tem]
                    qury_exist_personbase_id = pd.DataFrame(qury_exist_personbase_tem).rename(
                        columns={1: 'name_id', 0: 'IDcard'})
                    save_person = data[data['IDcard'].isin(qury_exist_personbase)]
                    save_person = pd.merge(qury_exist_personbase_id, save_person, on='IDcard').drop(
                        columns=['name', 'IDcard']).to_dict('records')
                    salaryscales = [SalaryScale(**item) for item in save_person]
                    session.add_all(salaryscales)
                    QMessageBox.information(None, '提示', '你导入成功%s条，失败%s条，明细如下！' % (len(salaryscales), len(data) - len(salaryscales)))
        except:
            QMessageBox.critical(None, '导入失败', '你没有选择文件！')
        self.load_table_data()

# 菜单
    def generate_menu(self, pos):
        menu = QMenu()
        viewitem = menu.addAction('查看')
        changeitem = menu.addAction('修改')
        deletitem = menu.addAction('删除')
        action = menu.exec(self.salaryscaletable.mapToGlobal(pos))
        posrow = self.salaryscaletable.currentRow()
        columns = self.salaryscaletable.columnCount()
        data = [self.salaryscaletable.item(posrow, i).text() for i in range(columns)]
        if action == changeitem:
            change = OperationSalaryScale('change',data)
            change.exec()
        elif action == deletitem:
            delete = OperationSalaryScale('delete',data)
            delete.exec()
        elif action == viewitem:
            view= OperationSalaryScale('view', data)
            view.exec()

        self.load_table_data()

    def additem(self):
        addsalary = OperationSalaryScale('add','')
        addsalary.exec()